/**
 * 维护机器人相关设置
 */
import { getLogger, Service } from '@gnlab/utils'
import { MemSubject } from '@gnlab/utils/rx'
import { OrderedMap } from 'immutable'
import type { Services } from '@/services'
import { type Word } from '@/services/common/definition'
import { requestAIChat } from './api'
import { type QywxGroup, type QywxConfig, type HistoryItem } from './definition'

export * from './definition'

export const logger = getLogger('services/features/robot')

export class Robot extends Service<Services> {
  private get qywxs() {
    return this.services.qywxs
  }
  private get auth() {
    return this.services.auth
  }

    registered() {
    //去掉此功能
    //void this.auth.accountId.then(() => {
    //  this.initLoad()
    //})
  }

  // 最新的企微配置 wxid => QywxConfig
  // map 里没有的企微说明当前没有工作中的配置
  private readonly configs$$ = new MemSubject<OrderedMap<string, QywxConfig>>(OrderedMap())
  readonly configs$ = this.configs$$.asStream()

  private initLoad() {
    void this.load()

    // 每隔 15 秒钟，刷新一次机器人配置
    setInterval(async () => this.load(), 15 * 1000)

    // 发现新企业微信时，触发刷新
    this.qywxs.bufferPrepared.subscribe(async () => this.load())
  }

  /**
   * 加载机器人配置
   */
  async load() {
    const wxids = this.qywxs.usableWxids.value
    const res = await requestAIChat<QywxGroup[] | null>('/wework-group/list-by-wx', {
      data: { wx_ids: wxids },
    })
    if (res.success) {
      let map = OrderedMap<string, QywxConfig>()
      ;(res.data ?? [])
        .filter(v => v.in_work_time)
        .forEach(group => {
          group.accounts.forEach(wxid => {
            map = map.set(wxid, {
              profileId: group.profile_id,
              runMode: group.config.run_mode,
              scope: group.config.range ?? [],
            })
          })
        })
      this.configs$$.next(map)
    } else {
      logger.error('机器人配置加载失败', res.error)
    }
  }

  /**
   * 获取回复
   */
  async getReply(profileId: number, history: HistoryItem[]) {
    return requestAIChat<{ messages: Word[]; by?: string }>(`/profiles/${profileId}/reply`, {
      data: { history },
    })
  }

  /**
   * 确认是否能连上 AI Chat 服务
   */
  async confirmAIChatStatus() {
    return new Promise<boolean>(resolve => {
      setTimeout(() => resolve(false), 5 * 1000)
      void requestAIChat('/health').then(res => resolve(res.success))
    })
  }

  async summary(profileId: number, history: HistoryItem[]) {
    return requestAIChat<{ summary: string }>('/match-reply/summary', {
      method: 'POST',
      data: {
        profile_id: profileId,
        history,
      },
    })
  }

  async addMatchReplyRule(data: {
    profileId: number
    summary: string
    match: string
    reply: Word
  }) {
    return requestAIChat('/match-reply/create', {
      method: 'POST',
      data: {
        list: [
          {
            profile_id: data.profileId,
            scene: data.summary,
            matches: [data.match],
            replies: [data.reply],
          },
        ],
      },
    })
  }
}
